package com.feiyisys.manager;

import com.feiyisys.utils.TencentVodUtil;
import com.qcloud.vod.model.VodUploadResponse;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 异步视频上传任务管理器
 */
@Slf4j
@Component
@EnableAsync
public class AsyncVideoUploadManager {

    @Resource
    private TencentVodUtil tencentVodUtil;

    // 存储上传任务状态
    private final Map<String, UploadTask> uploadTasks = new ConcurrentHashMap<>();
    private final AtomicLong taskIdGenerator = new AtomicLong(1000);

    /**
     * 上传任务状态
     */
    @Data
    public static class UploadTask {
        private String taskId;
        private String fileName;
        private UploadStatus status;
        private Integer progress; // 进度 0-100
        private String fileId;
        private String mediaUrl;
        private String coverUrl;
        private String errorMessage;
        private Long startTime;
        private Long endTime;
        
        public enum UploadStatus {
            PENDING,    // 等待中
            UPLOADING,  // 上传中
            SUCCESS,    // 成功
            FAILED      // 失败
        }
    }

    /**
     * 提交异步上传任务
     */
    public String submitUploadTask(MultipartFile videoFile, MultipartFile coverFile) {
        String taskId = "TASK_" + System.currentTimeMillis() + "_" + taskIdGenerator.incrementAndGet();
        
        UploadTask task = new UploadTask();
        task.setTaskId(taskId);
        task.setFileName(videoFile.getOriginalFilename());
        task.setStatus(UploadTask.UploadStatus.PENDING);
        task.setProgress(0);
        task.setStartTime(System.currentTimeMillis());
        
        uploadTasks.put(taskId, task);
        
        // 异步执行上传
        executeUploadAsync(taskId, videoFile, coverFile);
        
        log.info("提交异步上传任务: {}", taskId);
        return taskId;
    }

    /**
     * 异步执行上传
     */
    @Async("taskExecutor")
    public void executeUploadAsync(String taskId, MultipartFile videoFile, MultipartFile coverFile) {
        UploadTask task = uploadTasks.get(taskId);
        if (task == null) {
            log.error("任务不存在: {}", taskId);
            return;
        }

        try {
            // 更新状态为上传中
            task.setStatus(UploadTask.UploadStatus.UPLOADING);
            task.setProgress(10);
            
            log.info("开始异步上传任务: {}, 文件: {}", taskId, videoFile.getOriginalFilename());

            // 执行上传（这里可以添加进度回调）
            VodUploadResponse response = tencentVodUtil.uploadVideo(videoFile, coverFile);
            
            // 更新任务状态
            task.setProgress(100);
            task.setStatus(UploadTask.UploadStatus.SUCCESS);
            task.setFileId(response.getFileId());
            task.setMediaUrl(response.getMediaUrl());
            task.setCoverUrl(response.getCoverUrl());
            task.setEndTime(System.currentTimeMillis());
            
            long duration = (task.getEndTime() - task.getStartTime()) / 1000;
            log.info("异步上传任务完成: {}, 耗时: {}秒", taskId, duration);
            
        } catch (Exception e) {
            log.error("异步上传任务失败: {}", taskId, e);
            task.setStatus(UploadTask.UploadStatus.FAILED);
            task.setErrorMessage(e.getMessage());
            task.setEndTime(System.currentTimeMillis());
        }
    }

    /**
     * 获取任务状态
     */
    public UploadTask getTaskStatus(String taskId) {
        return uploadTasks.get(taskId);
    }

    /**
     * 获取所有任务
     */
    public Map<String, UploadTask> getAllTasks() {
        return new ConcurrentHashMap<>(uploadTasks);
    }

    /**
     * 清理完成的任务（可选）
     */
    public void cleanupCompletedTasks(long maxAgeMinutes) {
        long cutoffTime = System.currentTimeMillis() - (maxAgeMinutes * 60 * 1000);
        uploadTasks.entrySet().removeIf(entry -> {
            UploadTask task = entry.getValue();
            return (task.getEndTime() != null && task.getEndTime() < cutoffTime);
        });
    }
}